<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    :visible.sync="visible"
    width="60%"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      autocomplete="off"
      ref="dataForm"
      class="carddPage2"
      
      label-width="120px"
    >
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
      >全选</el-checkbox>
      <el-checkbox-group v-model="checkedlabel" @change="handleCheckedCitiesChange">
        <el-collapse v-model="activeNames">
          <el-collapse-item title="人脸识别" name="1">
            <el-checkbox
              border
              size="medium"
              v-for="item in antuList"
              :key="item.id"
              :label="item.id"
              v-if="1==item.type"
              style="margin:5px;width:200px;overflow:hidden"
            >{{item.name}}</el-checkbox>
          </el-collapse-item>

          <el-collapse-item title="刷卡机" name="2">
            <el-checkbox
              border
              size="medium"
              v-for="item in antuList"
              :key="item.id"
              :label="item.id"
              v-if="3==item.type"
              style="margin:5px;width:200px;overflow:hidden"
            >{{item.name}}</el-checkbox>
          </el-collapse-item>
        </el-collapse>
      </el-checkbox-group>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { treeDataTranslate } from "@/utils";
import TakePhoto from "@/components/takePhoto";

export default {
  components: { TakePhoto },

  data() {
    return {
      isIndeterminate: true,
      checkAll: false,
      visible: false,
      visibleTree: false,
      addOrUpdateVisible: false,
      fileList: [],
      activeNames: ["1"],
      activeName: "first",
      posiList: [],
      menuList: [],
      radio1: 0,
      antuList: [],
      checkedlabel: [],
      expendKey: [],
      menuListTreeProps: {
        children: "children",
        label: "name"
      },
      posiListTreeProps: {
        children: "children",
        label: "lable"
      },
      dataForm: {},
      dataRule: {
        name: [{ required: true, message: "姓名不能为空", trigger: "blur" }]
      },
      tempKey: -666666 // 临时key, 用于解决tree半选中状态项不能传给后台接口问题. # 待优化
    };
  },
  methods: {
    onChange(file, fileList) {
      const isIMAGE = file.name.substring(file.name.lastIndexOf(".") + 1);
      const isLt1M = file.size / 1024 / 1024;
      if (isIMAGE !== "jpg" && isIMAGE !== "png" && isIMAGE !== "jpeg") {
        this.$message.error("上传文件只能是jpg和png格式!");
        this.fileList.length = 0;
      }
      if (isLt1M > 1) {
        this.$message.error("上传文件大小不能超过 1MB!");
        this.fileList.length = 0;
      }
      let reader = new FileReader(); //html5读文件
      //转BASE64
      reader.readAsDataURL(file.raw);
      reader.onload = e => {
        let base64Str = e.target.result;
        //读取完毕后调用接口
        let imgData = base64Str.split(",")[1];
        console.log(base64Str);
        this.setImgUrl([base64Str]);
      };

      return isIMAGE && isLt1M;
    },
    handleRemove(val, fileList) {},
    beforeAvatarUpload() {},
    init(id) {
      this.dataForm = {
        id: "",
        cardStr: "",
        name: "",
        phone: "",
        roleId: "",
        idCard: "",
        gateIds: "",
        isOut: "0"
      };
      this.dataForm.id = id || "";

      this.$http({
        url: this.$http.adornUrl("/sys/org/list"),
        method: "POST",
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.posiList = data.list;
      });
      this.$http({
        url: this.$http.adornUrl("/sys/employee/info"),
        method: "POST"
      }).then(({ data }) => {
        this.antuList = data.gates.filter(
          item => item.type == 1 || item.type == 3
        );
        this.checkedlabel = [];
        this.visible = true;
        // if (data.entity) {
        //   Object.assign(this.dataForm, data.entity);
        //   this.fileList = [{ name: "照片", file: data.entity.headPortrait }];
        //   if (data.entity.gateIds) {
        //     this.checkedlabel = data.entity.gateIds.split(",");
        //   }
        // }
        this.handleCheckedCitiesChange(this.checkedlabel);
      });
    },
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true;
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id);
      });
    },
    handleCheckedCitiesChange(data) {
      let checkedCount = data.length;
      this.checkAll = checkedCount === this.antuList.length;
      this.isIndeterminate =
        checkedCount > 0 && checkedCount < this.antuList.length;
    },
    handleCheckAllChange(val) {
      this.checkedlabel = val ? this.antuList.map(item => item.id) : [];
      this.isIndeterminate = false;
    },
    getCardStr() {
      this.$http({
        url: this.$http.adornUrl("/sys/employee/set_card_str"),
        method: "post",
        data: this.$http.adornData()
      }).then(({ data }) => {
        if (data.code == 0) {
          Object.assign(this.dataForm, { cardStr: data.card_str });
        }
      });
    },
    setImgUrl(imgList) {
      this.$http({
        url: this.$http.adornUrl("/sys/employee/upload/img"),
        method: "post",
        data: this.$http.adornData({
          photo: imgList[0].split(";")[1]
        })
      }).then(({ data }) => {
        if (data.code == 0) {
          this.dataForm = Object.assign({}, this.dataForm, {
            headPortrait: data.url
          });
        }
      });
    },
    roleNodeClick(data) {
      if (data.type == "1") {
        Object.assign(this.dataForm, {
          roleId: data.value,
          roleName: data.lable
        });
        this.visibleTree = false;
      }
    },
    handleClick() {},
    // 表单提交
    dataFormSubmit() {
      this.$http({
        url: this.$http.adornUrl("/employee/updateEidsAndMids"),
        method: "post",
        data: this.$http.adornData({
          eids: this.dataForm.id,
          mids: this.checkedlabel.join(",")
        })
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.$message({
            message: data.msg || "操作成功",
            type: "success",
            duration: 1500,
            onClose: () => {
              this.visible = false;
              this.$emit("refreshDataList");
            }
          });
        } else {
          this.$message.error(data.msg);
        }
      });
    }
  }
};
</script>
<style  >
.el-popover {
  max-height: 320px;
  overflow-y: auto;
}
.carddPage2 .el-collapse {
  border: none;
}
.carddPage2 .el-collapse-item__header {
  background-color: #f2f2f2;
  margin-top: 5px;
  padding-left: 10px;
  font-weight: 600;
}
</style>
